package patrol.mobile.com.mobilepatrol.activity.track;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.dl7.recycler.listener.OnRecyclerViewItemClickListener;
import com.dl7.recycler.listener.OnRecyclerViewItemLongClickListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.realm.Realm;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.adapter.TrackListAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.PatrolDetailInfoBean;
import patrol.mobile.com.mobilepatrol.bean.PatrolInfoBean;
import patrol.mobile.com.mobilepatrol.manager.CarManager;
import patrol.mobile.com.mobilepatrol.manager.RouteManager;
import patrol.mobile.com.mobilepatrol.manager.TrackManager;
import patrol.mobile.com.mobilepatrol.persenter.TrackUpPer;
import patrol.mobile.com.mobilepatrol.persenter.UploadPicsPresenter;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.view.BridgeUpView;
import patrol.mobile.com.mobilepatrol.view.UploadImgView;
import patrol.mobile.com.mobilepatrol.widget.dialog.AppleDialog;

/**
 * Created by apple on 17/11/6.
 */

public class TrackListActivity extends BaseActivity implements BridgeUpView , UploadImgView {
    @BindView(R.id.iv_end_title)
    ImageView iv_end_title;

    @BindView(R.id.recycler)
    RecyclerView recyclerView;

    private TrackListAdapter mAdapter;
    private List<PatrolInfoBean> mList = new ArrayList<>();
    private String upID;

    @Override
    protected int attachLayoutRes() {
        return R.layout.comment_list;
    }

    @Override
    public void setListener() {
        //查看修改
        mAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(TrackListActivity.this, AddTrackActivity.class);
                intent.putExtra("alter", true);
                intent.putExtra("ID", mList.get(position).ID);
                startActivity(intent);
                CommonUtil.openNewActivityAnim(TrackListActivity.this, false);
            }
        });
        mAdapter.setOnItemLongClickListener(new OnRecyclerViewItemLongClickListener() {
            @Override
            public boolean onItemLongClick(View view, final int position) {
                final AppleDialog dialog = new AppleDialog(TrackListActivity.this,R.style.Dialog,"确认删除？");
                dialog.show();
                dialog.setmListener(new AppleDialog.SureListener() {
                    @Override
                    public void onSure() {

                        TrackManager.delPatrol(mList.get(position).ID);
                        mList = TrackManager.getAllList();
                        mAdapter.updateItems(mList);
                        dialog.dismiss();
                    }
                });

                return false;
            }
        });


    }
    @Override
    protected void onResume() {
        super.onResume();
        mList = TrackManager.getAllList();
        mAdapter.updateItems(mList);
    }
    @Override
    public void initData() {
        mList = TrackManager.getAllList();
        mAdapter.updateItems(mList);
        recyclerView.setAdapter(mAdapter);
    }
    @Override
    public void initView() {
        super.initView();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new TrackListAdapter(this, mList);
    }

    @Override
    public void initTitle() {
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(TrackListActivity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("巡道列表");
        iv_right_title.setVisibility(View.VISIBLE);
        iv_right_title.setImageResource(R.mipmap.add);
        iv_right_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CarManager.isNull()||RouteManager.isNull()){
                    showToast("请先初始化车辆或路线");
                    return;
                }
                startActivity(AddTrackActivity.class);
                CommonUtil.openNewActivityAnim(TrackListActivity.this, false);
            }
        });

    }
    /**
     * 上传
     */
    public void upload(final String id){
        upID = id;
        PatrolInfoBean p = PatrolApp.realm.copyFromRealm(TrackManager.getPatrol(id));
        String upString = GsonUtil.GsonString(p);
        showLoading();
        TrackUpPer per = new TrackUpPer(this,this,upString,id);
        per.up(Urls.updateTrack,"PatrolInfoBean");
        //uploadImg(id);

    }

    private void uploadImg(String id) {
        List<PatrolDetailInfoBean> detailInfos = TrackManager.getAllDetailList(id);
        for (int i=0;i<detailInfos.size();i++){
            PatrolDetailInfoBean d = detailInfos.get(i);
            String ID = d.ID;
            String pn = d.photoNumber;
            if (pn!=null&&!pn.equals("")){
                String[] imgs = pn.split(",");
                uploadImg(ID,imgs);
            }

        }
    }
    /**
     * 一个明细的多张图片
     */
    private void uploadImg(String id,String[] imgs) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .addFormDataPart("bizID", id);

        //多张图片
        for (int i = 0; i < imgs.length; i++) {
            File file = new File(imgs[i]);//filePath 图片地址
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            builder.addFormDataPart("file", imgs[i], imageBody);//"imgfile"+i 后台接收图片流的参数名
        }

        List<MultipartBody.Part> parts = builder.build().parts();
        UploadPicsPresenter picsPresenter = new UploadPicsPresenter(this,parts);
        picsPresenter.uploadTrackImg();

    }
    /**
     * 继续巡道
     */
    public void goDetail(final String id){
        Intent intent = new Intent(TrackListActivity.this,TrackDetailListActivity.class);
        intent.putExtra("ID",id);
        startActivity(intent);
        CommonUtil.openNewActivityAnim(TrackListActivity.this,false);
    }

    @Override
    public void onError(String s) {
        showToast(s);
    }

    @Override
    public void onSuccess(String s) {
        showToast(s);
        PatrolApp.realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                List<PatrolInfoBean> mlist = realm.where(PatrolInfoBean.class).equalTo("ID",upID).findAll();
                PatrolInfoBean p = mlist.get(0);
                p.status = 1;
                List<PatrolDetailInfoBean> dList = p.detailInfoBeans;
                for (int i=0;i<dList.size();i++){
                    dList.get(i).statu = 1;
                }
            }
        });
        mList = TrackManager.getAllList();
        mAdapter.updateItems(mList);
    }

    @Override
    public void upImgSuccess(String s) {
        showToast("图片上传成功");
    }

    @Override
    public void upImgError(String s) {
        showToast("图片上传失败");
    }
}
